<template>
	<view>
		<view style="position: relative;">
			<!-- 选择单张图片 -->
			<view class="showImg-ss" style="position: relative; ">
				<view class="angle_mark" @click="getImg">
					<image class="img icon-edit-avatar"></image>
				</view>
				<image :src="avatarUrl" @click="lookImg(avatarUrl)" mode="aspectFill" class="img"
					:class="{'icon-default-avatar':!(avatarUrl)}"
					style=" border: 4rpx solid #fff; border-radius: 100%;"></image>
				<view class="progress-box" :style="{width: progress + '%'}" :class="{fail:uploadState=='fail'}"
					v-if="uploadState=='loading'">
					<text v-if="uploadState=='success'">上传完成</text>
					<text v-if="uploadState=='fail'">上传失败</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		uploadfile
	} from '@/api/user.js'

	export default {
		name: 'rf-uploadfile',
		props: {
			value: {
				type: String,
				default: ""
			},
		},
		data() {
			return {
				progress: 0,
				uploadState: "fail",
				avatarUrl: "",
				localPath: ""
			}
		},
		watch: {
			value(val) {
				if (val == "" || val == null) return
				this.avatarUrl = val
			},
		},
		methods: {


			// 选择图片
			getImg: function(e) {
				uni.chooseImage({
					count: 1,
					// sizeType: "compressed", // sizeType压缩图片
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'],
					success: (res) => {
						console.log("选择图片", e);
						console.log(res);
						// 本地显示
						this.localPath = res.tempFilePaths[0]

						// 上传
						this.uploadState = 'loading'
						this.multipartUpload(this.localPath)
					}
				})

			},
			lookImg(url) {
				if (url.startsWith("http")) {
					const urls = [url]
					const current = 1
					uni.previewImage({
						urls,
						current
					})
				}

			},
			//删除图片
			delImg() {
				// this.imgArr.splice(0);
			},

			// 开始分片上传。
			async multipartUpload(localPath) {
				let _that = this
				uploadfile(localPath).then(res => {
					setTimeout(() => {
						_that.avatarUrl = res;
						_that.$emit('input', res);
					}, 1000);
				})

			},
		}
	}
</script>

<style lang="scss">
	.getImg-ss {
		height: 160rpx;
		width: 160rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-style: dashed;
		border-width: 1rpx;
		color: darkgray;
	}


	// 角标
	.angle_mark {
		position: absolute;
		right: 0rpx;
		bottom: 0rpx;
		z-index: 990;
		width: 40rpx;
		height: 40rpx;

		.img {
			width: 100%;
			height: 100%;
		}


		// transform: rotate(45deg);
	}

	.img {
		height: 160rpx;
		width: 160rpx;
	}

	.showImg-ss {
		height: 160rpx;
		width: 160rpx;

		.progress-box {
			position: absolute;
			z-index: 991;
			bottom: 0px;
			left: 0px;
			height: 20%;
			background-color: #007768;

			&.success {
				width: 100%;
				background-color: #007768;
			}

			&.fail {
				width: 100%;
				background-color: red;
			}

			text {
				display: flex;
				justify-content: center;

				font-size: 10px;
				color: #fff;
			}
		}
	}
</style>